import * as THREE from 'three';
import { Vec3 } from '@/core/types';
import { Entity } from './Entity';
import { EntityType, AIState, EntityStats } from './types';
import { WorldManager } from '@/world/WorldManager';
import { ItemDropManager } from '@/world/ItemDrop';

export abstract class HostileEntity extends Entity {
  protected target?: Vec3;
  protected targetEntity?: string;
  protected attackCooldown = 0;
  protected attackInterval = 1.5; // 1.5秒攻击间隔
  protected lastPlayerPosition?: Vec3;
  protected chaseSpeed: number;

  constructor(id: string, type: EntityType, position: Vec3, worldManager: WorldManager, stats: EntityStats, itemDropManager?: ItemDropManager) {
    super(id, type, position, worldManager, stats, itemDropManager);
    this.chaseSpeed = stats.moveSpeed * 1.5; // 追击时速度更快
  }

  protected initializeAI(): void {
    this.ai = {
      state: AIState.IDLE,
      stateTimer: 0,
      lastStateChange: Date.now()
    };
  }

  protected processAI(deltaTime: number): void {
    if (!this.ai) return;

    // 更新攻击冷却
    if (this.attackCooldown > 0) {
      this.attackCooldown -= deltaTime;
    }

    switch (this.ai.state) {
      case AIState.IDLE:
        this.processIdleState(deltaTime);
        break;
      case AIState.WANDERING:
        this.processWanderingState(deltaTime);
        break;
      case AIState.FOLLOWING:
        this.processFollowingState(deltaTime);
        break;
      case AIState.ATTACKING:
        this.processAttackingState(deltaTime);
        break;
      case AIState.DEAD:
        // 死亡状态不需要处理
        break;
    }
  }

  private processIdleState(deltaTime: number): void {
    // 检测玩家
    const playerInRange = this.detectPlayer();
    if (playerInRange) {
      this.startChasing(playerInRange);
      return;
    }

    // 随机开始游荡
    if (Math.random() < 0.02) { // 2%概率开始游荡
      this.startWandering();
    }
  }

  private processWanderingState(deltaTime: number): void {
    // 检测玩家
    const playerInRange = this.detectPlayer();
    if (playerInRange) {
      this.startChasing(playerInRange);
      return;
    }

    // 简单的游荡逻辑
    if (!this.target) {
      this.startWandering();
      return;
    }

    const distance = this.getDistanceTo(this.target);
    if (distance < 1.0 || this.ai!.stateTimer > 8) {
      // 到达目标或游荡时间过长，切换到闲置
      this.ai!.state = AIState.IDLE;
      this.ai!.stateTimer = 0;
      this.target = undefined;
      this.velocity.x = 0;
      this.velocity.z = 0;
    } else {
      this.moveTowards(this.target, this.stats.moveSpeed);
    }
  }

  private processFollowingState(deltaTime: number): void {
    if (!this.target) {
      this.ai!.state = AIState.IDLE;
      return;
    }

    const distance = this.getDistanceTo(this.target);
    
    // 如果玩家太远，停止追击
    if (distance > this.stats.detectionRange * 2) {
      this.ai!.state = AIState.IDLE;
      this.target = undefined;
      this.velocity.x = 0;
      this.velocity.z = 0;
      return;
    }

    // 如果足够接近，开始攻击
    if (distance <= (this.stats.attackRange || 2)) {
      this.ai!.state = AIState.ATTACKING;
      this.ai!.stateTimer = 0;
      return;
    }

    // 继续追击
    this.moveTowards(this.target, this.chaseSpeed);
    this.lastPlayerPosition = { ...this.target };
  }

  private processAttackingState(deltaTime: number): void {
    if (!this.target) {
      this.ai!.state = AIState.IDLE;
      return;
    }

    const distance = this.getDistanceTo(this.target);
    
    // 如果玩家逃跑了，继续追击
    if (distance > (this.stats.attackRange || 2) * 1.5) {
      this.ai!.state = AIState.FOLLOWING;
      this.ai!.stateTimer = 0;
      return;
    }

    // 执行攻击
    if (this.attackCooldown <= 0) {
      this.performAttack();
      this.attackCooldown = this.attackInterval;
    }

    // 攻击时稍微移动向玩家
    if (distance > 1.0) {
      this.moveTowards(this.target, this.stats.moveSpeed * 0.5);
    }
  }

  private detectPlayer(): Vec3 | null {
    // 这里应该从游戏系统获取玩家位置
    // 现在简化为检查是否有存储的玩家位置
    if (this.lastPlayerPosition) {
      const distance = this.getDistanceTo(this.lastPlayerPosition);
      if (distance <= this.stats.detectionRange) {
        return this.lastPlayerPosition;
      }
    }
    return null;
  }

  private startChasing(playerPosition: Vec3): void {
    if (this.ai) {
      this.ai.state = AIState.FOLLOWING;
      this.ai.stateTimer = 0;
      this.target = playerPosition;
    }
  }

  private startWandering(): void {
    if (!this.ai) return;

    // 选择随机游荡目标
    const angle = Math.random() * Math.PI * 2;
    const distance = 5 + Math.random() * 10;
    
    this.target = {
      x: this.position.x + Math.cos(angle) * distance,
      y: this.position.y,
      z: this.position.z + Math.sin(angle) * distance
    };

    this.ai.state = AIState.WANDERING;
    this.ai.stateTimer = 0;
  }

  private performAttack(): void {
    console.log(`${this.type} ${this.id} attacks for ${this.stats.attackDamage} damage!`);
    
    // 这里应该对玩家造成伤害
    // 在实际游戏中会调用玩家的takeDamage方法
    this.onAttack();
  }

  protected abstract onAttack(): void;

  // 更新玩家位置（由游戏系统调用）
  public updatePlayerPosition(playerPosition: Vec3): void {
    this.lastPlayerPosition = playerPosition;
  }

  // 受到攻击时的反应
  protected onDamage(amount: number): void {
    // 敌对生物受伤时会变得更加激进
    if (this.ai && this.lastPlayerPosition) {
      this.ai.state = AIState.FOLLOWING;
      this.target = this.lastPlayerPosition;
      this.chaseSpeed = this.stats.moveSpeed * 2; // 受伤后移动更快
    }
  }

  protected onDeath(): void {
    // 敌对生物死亡时掉落经验和物品
    this.dropLoot();
  }

  protected abstract dropLoot(): void;

  // 检查是否应该在夜晚生成
  public static shouldSpawnAtNight(): boolean {
    return true; // 大多数敌对生物在夜晚生成
  }

  // 检查是否应该在光照较暗的地方生成
  public static shouldSpawnInDarkness(): boolean {
    return true;
  }
}